package com.webfileupload.servlets;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

//使用了fileupload组件 
public class Upload extends HttpServlet {

	private static final long serialVersionUID = 3927535486482875751L;

	private String[] filenames;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");

		if (upload(request, response)) {
			saveToDB();
		}

	}

	@SuppressWarnings("rawtypes")
	public boolean upload(HttpServletRequest request,
			HttpServletResponse response) {
		boolean flag = false;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List items = upload.parseRequest(request);
			Iterator it = items.iterator();
			int i = 0;
			while (it.hasNext()) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField()) {
					if (!item.getName().equals("") && item.getName() != null) {
						File tmpfile = new File(item.getName());
						filenames[i++] = tmpfile.getName();
						File file = new File("c:\\", tmpfile.getName());
						item.write(file);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	public void saveToDB() {
		if (filenames != null) {
			String url = "jdbc:mysql:/localhost/fileupload";
			String username = "root";
			String password = "jqbmyql";
			String sql = "insert into filemanager(filename,time) values(?,?)";
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				Connection conn = DriverManager.getConnection(url, username,
						password);
				PreparedStatement pstm = conn.prepareStatement(sql);
				for (int i = 0; i < filenames.length; i++) {
					pstm.setString(1, filenames[i]);
					SimpleDateFormat sdf = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					pstm.setString(2, sdf.format(new Date()));
					pstm.executeUpdate();
				}
				pstm.close();
				conn.close();
				System.out.println("保存成功");
			} catch (Exception e) {
				System.out.println("保存失败");
				e.printStackTrace();
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
